package com.zhuoyue.interceptor;

import com.zhuoyue.common.enumeration.RequestPathEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @author wjming
 */
@Slf4j
@Component
public class TraceIdInterceptor implements HandlerInterceptor {
    private static final String FLAG = "EagleEye-TraceID";
    private static final String APP_VERSION_HEADER_KEY = "app_version";
    private static final Integer APP_VERSION = 2;
    private static final String V2 = "v2";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {
        createTraceId(request);
        return true;
    }

    /**
     * 生成链路ID
     *
     * @param request
     */
    private void createTraceId(HttpServletRequest request) {
        MDC.clear();
        String traceId = request.getHeader(FLAG);
        if (StringUtils.isEmpty(traceId)) {
            if (null == MDC.get(FLAG)) {
                MDC.put(FLAG, UUID.randomUUID().toString());
            }
        } else {
            MDC.put(FLAG, traceId);
        }
    }
}
